<%@ Page Trace="false" Language="C#" %>
<%@ Import Namespace="System.IO" %>

<H2>BinaryReader / BinaryWriter</H2>
<script runat=server>

	// File we are going to create
	
	const string FileToReadWrite = "simple.bin";
	
	protected void Page_Load( object sender, EventArgs e )
	{
		BinaryWriter bw;
		FileStream fs;
		string filename;
		Stream stream;

		filename = Server.MapPath(FileToReadWrite);
		
		stream = new FileStream( filename, FileMode.Create );
		bw = new BinaryWriter( stream );
		
		long l = 0x123456789abcdef;
		int i = 0x12345678;
		char c = 'c';
		float f = 1.5f;
		Decimal d = 100.2m;
		
		bw.Write( "a string" );
		bw.Write( l );
		bw.Write( i );
		bw.Write( c );
		bw.Write( f );
		bw.Write( d );
		
		stream.Close();
				
		
	}

	// Outputs the file offset

	protected void WriteFileOffset( int offset )
	{
		Response.Write( offset.ToString("X6") );
		Response.Write( " ");	
	}
		
	protected void WriteContentsToResponse( BinaryReader reader )
	{
		byte b;
		int count = 0;
		int offset = 0;
		const int maxBytes = 16;
		byte[] bytes = new Byte[16];

		Response.Write("<pre>");

		try
		{
			WriteFileOffset( offset );

			for(;;)
			{
				b = reader.ReadByte();

				Response.Write( b.ToString("X2") );
				count++;

				if ( count == maxBytes )
				{
					Response.Write("<BR>");
					count = 0;
					offset += maxBytes;
					WriteFileOffset( offset );
				}
				else
				{
					Response.Write( " " );
				}
			}
		}

		// Catch expected end of stream exception

		catch( EndOfStreamException e )
		{
		}

		// Unexpected exception so throw out to ASP.NET

		catch( Exception e )
		{
			throw e;
		}
		Response.Write("</pre>");

	}

</script>



<%
	string fileToRead;
	Stream stream;

	fileToRead = Server.MapPath(FileToReadWrite);
	stream = File.Open( fileToRead, FileMode.Open );
	WriteContentsToResponse( new BinaryReader( stream ) );
	stream.Close();
	

%>

